package com.example.controller;

import com.example.domain.Book;
import com.example.domain.User;
import com.example.dto.BookAddDTO;
import com.example.dto.BookQueryDTO;
import com.example.dto.BookResponseDTO;
import com.example.dto.BookUpdateDTO;
import com.example.dto.PageQueryRequestDTO;
import com.example.dto.PageResponseDTO;
import com.example.service.BookService;
import com.example.service.OperationLogService;
import com.example.service.UserService;
import com.example.util.Result;
import com.example.vo.BookWithLocationVO;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 图书管理控制器
 * 
 * @author HP
 * @description 图书管理相关接口
 * @createDate 2025-08-27
 */
@RestController
@RequestMapping("/api/books")
public class BookController {

    @Autowired
    private BookService bookService;
    
    @Autowired
    private OperationLogService operationLogService;
    
    @Autowired
    private UserService userService;

    /**
     * 获取当前登录用户ID
     * @return 用户ID
     */
    private Long getCurrentUserId() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth != null && auth.isAuthenticated() && !"anonymousUser".equals(auth.getName())) {
            String username = auth.getName();
            try {
                // 通过用户名查询用户ID
                User user = userService.getUserByUsername(username);
                return user != null ? user.getId() : null;
            } catch (Exception e) {
                // 如果查询失败，返回null
                return null;
            }
        }
        return null;
    }

    /**
     * 添加图书（管理员权限）
     * @param bookAddDTO 图书信息
     * @return 操作结果
     */
    @PostMapping
    @PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_SUPER_ADMIN')")
    public Result addBook(@RequestBody @Valid BookAddDTO bookAddDTO, HttpServletRequest request) {
        try {
            Result result = bookService.addBook(bookAddDTO);
            if (result.getCode() == 200) {
                // 获取当前登录用户ID
                Long operatorId = getCurrentUserId();
                if (operatorId != null) {
                    // 从返回结果中获取新创建的图书ID
                    Object data = result.getData();
                    Long bookId = null;
                    if (data instanceof Book) {
                        bookId = ((Book) data).getId();
                    }
                    // 记录操作日志
                    operationLogService.recordLog(
                        operatorId, 
                        bookId != null ? bookId : 0L, // 使用图书ID作为实体ID
                        1, // 1表示图书实体类型
                        "添加图书：" + bookAddDTO.getTitle()
                    );
                }
            }
            return result;
        } catch (Exception e) {
            return Result.error("添加图书失败：" + e.getMessage());
        }
    }

    /**
     * 更新图书信息（管理员权限）
     * @param bookUpdateDTO 图书更新信息
     * @return 操作结果
     */
    @PutMapping
    @PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_SUPER_ADMIN')")
    public Result updateBook(@RequestBody @Valid BookUpdateDTO bookUpdateDTO, HttpServletRequest request) {
        try {
            Result result = bookService.updateBook(bookUpdateDTO);
            if (result.getCode() == 200) {
                // 获取当前登录用户ID
                Long operatorId = getCurrentUserId();
                if (operatorId != null) {
                    // 记录操作日志
                    operationLogService.recordLog(
                        operatorId, 
                        bookUpdateDTO.getId(), 
                        1, // 1表示图书实体类型
                        "更新图书信息：ID=" + bookUpdateDTO.getId() + ", 标题=" + bookUpdateDTO.getTitle()
                    );
                }
            }
            return result;
        } catch (Exception e) {
            return Result.error("更新图书失败：" + e.getMessage());
        }
    }

    /**
     * 删除图书（管理员权限）
     * @param id 图书ID
     * @return 操作结果
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_SUPER_ADMIN')")
    public Result deleteBook(@PathVariable Long id, HttpServletRequest request) {
        try {
            // 先获取图书信息，用于日志记录
            Book book = bookService.getById(id);
            if (book == null) {
                return Result.error("图书不存在");
            }
            
            Result result = bookService.removeBook(id);
            
            if (result.getCode() == 200) {
                // 获取当前登录用户ID
                Long operatorId = getCurrentUserId();
                if (operatorId != null) {
                    // 记录操作日志
                    operationLogService.recordLog(
                        operatorId, 
                        id, 
                        1, // 1表示图书实体类型
                        "删除图书：ID=" + id + ", 标题=" + book.getTitle()
                    );
                }
            }
            return result;
        } catch (Exception e) {
            return Result.error("删除图书失败：" + e.getMessage());
        }
    }

    /**
     * 获取图书详情
     * @param id 图书ID
     * @return 图书详情
     */
    @GetMapping("/{id}")
    public Result getBookById(@PathVariable Long id) {
        try {
            if (id == null || id <= 0) {
                return Result.error("图书ID无效");
            }
            BookWithLocationVO bookWithLocation = bookService.getBookWithLocationById(id);
            if (bookWithLocation == null) {
                return Result.error("图书不存在");
            }
            return Result.success(bookWithLocation);
        } catch (Exception e) {
            return Result.error("查询图书详情失败：" + e.getMessage());
        }
    }

    /**
     * 分页查询图书
     * @param queryDTO 查询条件
     * @return 分页结果
     */
    @GetMapping("/page")
    public Result getBooksByPage(@Valid BookQueryDTO queryDTO) {
        try {
            Book queryBook = new Book();
            queryBook.setTitle(queryDTO.getTitle());
            queryBook.setAuthor(queryDTO.getAuthor());
            queryBook.setPublisher(queryDTO.getPublisher());
            queryBook.setCategoryId(queryDTO.getCategoryId());
            queryBook.setBookshelfId(queryDTO.getBookshelfId());
            queryBook.setBookStatus(queryDTO.getBookStatus());
            
            List<BookWithLocationVO> booksWithLocation = bookService.queryBooksWithLocation(queryBook);
            return Result.success(booksWithLocation);
        } catch (Exception e) {
            return Result.error("查询图书失败：" + e.getMessage());
        }
    }

    /**
     * 根据分类ID查询图书
     * @param categoryId 分类ID
     * @return 图书列表
     */
    @GetMapping("/category/{categoryId}")
    public Result getBooksByCategory(@PathVariable Long categoryId) {
        try {
            if (categoryId == null || categoryId <= 0) {
                return Result.error("分类ID无效");
            }
            List<Book> books = bookService.getBooksByCategoryId(categoryId);
            return Result.success(books);
        } catch (Exception e) {
            return Result.error("查询分类图书失败：" + e.getMessage());
        }
    }

    /**
     * 获取所有图书分类
     * @return 分类列表
     */
    @GetMapping("/categories")
    public Result getAllCategories() {
        try {
            return Result.success(bookService.getAllCategories());
        } catch (Exception e) {
            return Result.error("获取分类列表失败：" + e.getMessage());
        }
    }
}